﻿define([
    'views/baseView',
    'models/crud/projectModel',
    'controllers/crud/projectMngr',
    'views/map/mapView',
    'text!templates/crud/project/projectMapContainer.html',
], function (BaseView, ProjectModel, ProjectController, MapView, HTMLTemplate) {

    var view = BaseView.extend({
        //el: $("#main"),
        mapView: undefined,
        currentProject: undefined,
        //currentProjectId: undefined,// this.options.projectId
        saving: false,
        render: function () {
            var that = this;
            toggleLoading(true);
            changeTopNavTitle("_projectMap");
            this.$el.children().remove();
            $("div[data-rel='crud_project']").remove();


            // minimize sidebar
            $("#menu-medium").trigger("click");
            $("#menu-thin").trigger("click");
            // TODO

            // Si es Modo Edicion viene projectId, sino viene solutionId
            var template = Handlebars.compile(HTMLTemplate);
            var html = template();
            this.$el.append(html);

            var updateSizes = function () {

                var h = $(window).height() - 40;
                $("#projectMap").height(h);
                $("#projectMap .generalinfo").height(h - 25);
                $("#projectMap .generalinfo .shapeinfo-container").height(h - 25 - 66);
            }
            // falta crear el metodo registerResizeEvents de forma general?
            registerResizeEvents("projectmap", updateSizes);
            updateSizes();

            //this.showFPCaseManager();

            // revisar lo que sigue
            setTimeout(function () {
                that.createMap();
            }, 300);
            this.registerEvents()


            $(".projectMapTask").on("removeView", function () {
                that.onRemoveView();
                that = null;
            });

            $(".projectMapTask").on("beforeRemoveView", function (event, callbackOk) {
                if (that.mapView && that.mapView.hasChanges) {
                    event.preventDefault();

                    // display popup to save or cancel
                    $("#projectMap").trigger("isOkToBack", [function (isOK) {
                        if (isOK) {
                            that.mapView.hasChanges = false; //force no changes 
                            callbackOk();
                        }
                    }]);

                }
            });

            
        },
        onRemoveView: function () {
            if (this.mapView) {
                this.mapView.removeView();
            }
            this.mapView = null;
            this.currentProject = null;
            $("#projectMapSidebar").off();

        },
        createMap: function () {

            if (!this.mapView) {
                this.mapView = new MapView();
                this.mapView.render("projectMap");

                // TODO: quitar esto una vez modificada la forma de cargar el mapa
                $("#projectMapSidebar").trigger("openProject");
            }
            // remover este disable, no lo uso
            //this.mapView.disableMap();

        },
        //showFPCaseManager: function () {
            // NO VA, carga el listado de FPCases.
        //    (new ProjectController()).showFPCaseList(this.$el);
        //    if (this.mapView) {
        //        this.mapView.disableMap();
        //    }
        //},
        registerEvents: function () {
            var that = this;
            $("#projectMapSidebar").on("openProject", function (evt) {

                //open project projectId
                that.mapView.enableMap();
                // poner condicion para agregar o no los controles al mapa.
                that.mapView.addControlsForBuild();

                var pModel = new ProjectModel();
                pModel.get(that.options.projectId, function (project) {
                    that.currentProject = project;
                    $("#projectMap .project-title").html(project.name);
                    // no quiero ocultar los botones.. Facu
                    //$("#projectMap .buttons-map div").hide();
                    // Esto que sigue es para los diferentes tipos de config (internacional, etc)
                    //var keyConfig = ".fpcase-" + project.fpCaseConfiguration.code;
                    //$("#projectMap " + keyConfig).show();

                    $("#projectMapSidebar").trigger("getGeoData", [that.options.projectId]);

                });
            });

            $("#projectMapSidebar").on("closeProject", function (evt) {
                if (that.mapView)
                    that.mapView.clearMap();
            });

            $("#projectMapSidebar").on("refreshProject", function (evt, projectId) {


                if (that.mapView && (!projectId || projectId == that.currentProject.projectId)) {

                    var projMod = new ProjectModel();
                    projMod.getGeoData(that.currentProject.projectId, function (getData) {
                        that.mapView.setMapData(getData, true);
                    });
                }

            });

            $("#projectMapSidebar").on("updateShapeContent", function (evt, projectId) {


                if (that.mapView && (!projectId || projectId == that.currentProject.projectId)) {
                    // obtener contenido de la figura y guardarlo en los atributos de la misma. sin guardar en base de datos
                    that.mapView.updateShapeContent();
                    //var projMod = new ProjectModel();
                    //projMod.getGeoData(that.currentProject.projectId, function (getData) {
                    //    that.mapView.setMapData(getData, true);
                    //});
                }

            });

            $("#projectMapSidebar").on("getGeoData", function (evt, projectId) {
                // get geodata info
                if (projectId)
                    that.currentProject.projectId = projectId;
                else
                    projectId = that.currentProject.projectId;

                var projMod = new ProjectModel();
                projMod.getGeoData(projectId, function (getData) {
                    that.mapView.setMapData(getData);
                    toggleLoading(false);
                });
            });

            $("#projectMapSidebar").on("getGeoAttributes", function (evt, callback) {
                (new ProjectModel()).getGeoAttributes(that.currentProject.projectId, function (geoAttr) {
                    callback(geoAttr);
                });
            });

            $("i[data-rel='toggle_edit']").click(function () {

                if ($("#" + that.mapView.mapElement).hasClass("editing")) {
                    // pasar a result mode
                    $("#projectMap").trigger("setMode", ["result"]);
                    $("#projectMap").trigger("removeControlsForBuild");
                } else {
                    // pasa a edition mode
                    $("#projectMap").trigger("setMode", ["free"]);
                    $("#projectMap").trigger("addControlsForBuild");
                }
            });

            //$("#projectMapSidebar").on("evaluateFPCase", function (evt) {
            //    if (that.currentProject) {
            //        var idFPCase = that.currentProject.idFPCase;
            //        require(['plugins/FastPath/js/controllers/fpcases/fpCases'], function (ProjectController) {
            //            (new ProjectController()).evaluateFPCase(idFPCase);
            //        });
            //    }
            //});

            $("#projectMapSidebar").on("afterFormSave", function (evt, id, name) {
                //$("#projectMapSidebar").trigger("markWithData"); // comentado el evento, Facu
                that.mapView.refreshLayerNameFromForm(name);
            });
            // No lo utilizare por ahora. No necesito saber si tienen datos asociados (POR AHORA)
            //$("#projectMapSidebar").on("markWithData", function (evt) {
            //    var projectId = that.currentProject.projectId;
            //    var projectMod = new ProjectModel();
            //    // TODO: dataInFPCase.. seria dataInProject
            //    projectMod.dataInFPCase(projectId, function (dataInFPCase) {
            //        that.mapView.markWithData(dataInFPCase);
            //    });
            //});

            $("#projectMapSidebar").on("saveProject", function (evt) {
                if (that.mapView.isValid()) {
                    that.saveProject();
                }
            });

            $("#projectMapSidebar").on("showFPCases", function (evt) {
                that.showFPCaseManager();
            });

            $("#projectMapSidebar").on("showSubcorridorForm", function (evt, subcorridorId) {

                (new ProjectController).editSubcorridorForm(that.$el, subcorridorId, function () {
                    // refrescar el subcorridor para que se vea el cambio de nombre si es que hubo
                });
            });

            // Modificando el asignar subcorridor por regiones
            $("#projectMapSidebar").on("assignDemandPerSubcorridor", function (evt) {

                (new ProjectController).editAssignDemandForm(that.$el, that.currentProject.projectId, function () {
                    // refrescar el subcorridor para que se vea el cambio de nombre si es que hubo
                });
            });

            $("#projectMapSidebar").on("showLinksAndNodeForm", function (evt, entityId, geoType, dataType, distance, caseId) {
                //entityId: id de nodo o ink
                // geoType: 1->nodo, 2->link
                // dataType: tipo de nodo o link
                // distance: adivina... si. la distancia.
                // caseId: -1 si es crear un nuevo case, >0 si es editar un case existente
                switch (geoType) {
                    case 1: // nodes
                        switch (dataType) {
                            case "INT_ROAD":
                                (new ProjectController).editRoadNodeForm(that.$el, entityId, caseId);
                                break;
                            case "INT_RAIL":
                                (new ProjectController).editRailNodeForm(that.$el, entityId, caseId);
                                break;
                            case "INT_INLAND_WATERWAY":
                                (new ProjectController).editIWWNodeForm(that.$el, entityId, caseId);
                                break;
                            case "INT_DISTRIBUTION_CENTER":
                                (new ProjectController).editDistributionNodeForm(that.$el, entityId, caseId);
                                break;
                            case "INT_COASTAL_SHIPPING":
                                (new ProjectController).editCoastalNodeForm(that.$el, entityId, caseId);
                                break;
                            case "INT_INTERMODAL_CONTAINER_TERMINAL":
                                (new ProjectController).editICTNodeForm(that.$el, entityId, caseId);
                                break;
                            case "INT_BORDER_POST":
                                (new ProjectController).editBorderPostNodeForm(that.$el, entityId, caseId);
                                break;
                            case "INT_SEAPORT":
                                (new ProjectController).editSeaportNodeForm(that.$el, entityId, caseId);
                                break;
                            case "INT_OVERSEAS_PORT":
                                (new ProjectController).editOverseasNodeForm(that.$el, entityId, caseId);
                                break;
                            case "INT_POPULATION_CENTER":
                                (new ProjectController).editPopulationCenterNodeForm(that.$el, entityId, caseId);
                                break;
                            case "INT_SIMPLE_NODE":
                                (new ProjectController).editSimpleNodeForm(that.$el, entityId, caseId);
                                break;
                        }
                        break;
                    case 2: // links
                        distance /= 1000; // m to km
                        distance = distance.toFixed(2);
                        switch (dataType) {
                            case "INT_ROAD":
                                (new ProjectController).editRoadLinkForm(that.$el, entityId, caseId, distance);
                                break;
                            case "INT_RAIL":
                                (new ProjectController).editRailLinkForm(that.$el, entityId, caseId, distance);
                                break;
                            case "INT_COASTAL":
                                (new ProjectController).editCoastalLinkForm(that.$el, entityId, caseId, distance);
                                break;
                            case "INT_INLAND_WATERWAY":
                                (new ProjectController).editIWWLinkForm(that.$el, entityId, caseId, distance);
                                break;
                            case "INT_MARINE_SHIPPING":
                                (new ProjectController).editMarineLinkForm(that.$el, entityId, caseId, distance);
                                break;
                        }
                        break;
                }
            });
        },
        saveProject: function () {

            if (this.saving)
                return;

            $("#mainLoading").show();

            var that = this;
            var mapData = this.mapView.getMapData();
            mapData.projectId = this.currentProject.projectId;

            var projectMod = new ProjectModel();
            this.saving = true;
            projectMod.setGeoData(mapData, function (data) {
                $("#mainLoading").hide();

                if (that.mapView)
                    that.mapView.updateMapData(data);

                showMessage("success", translate("_projectSaved"));
                
                that.saving = false;


                // call nodejs
                //triggerNodeJsEvent("FPCaseAfterSave", mapData.projectId);



            }, function (error) {
                $("#mainLoading").hide();
                that.saving = false;
                if (that.mapView)
                    that.mapView.errorInSave();
            });
        }

    });
    return view;
});